/**
 * @FileName: PackageService.java
 * @Author
 * @Description:
 * @Date 2016年1月11日 下午4:40:18
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import cn.hpclub.server.model.LocalizedConfig;
import cn.hpclub.server.util.DateKit;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.constant.ClientApiConstant;
import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.model.Package;
import cn.hpclub.server.util.InterfaceUtil;
import cn.hpclub.server.util.ResultCode;

public class PackageService{
    private static final Logger  logger  = LoggerFactory.getLogger(PackageService.class);
    public static PackageService service = new PackageService();

    public static final String[]        headesExport  = { "套餐名称", "号码类型", "资费代码", "资费(元/月)", "预存费用(元)", "品牌编码", "特点描述", "创建时间",
            "创建人", "创建人的机构", "授权属性","属地化城市","是否启用"};
    public static final String[]        columnsExport = { "name", "type", "tariff_code", "monthly_charge", "predeposited",
            "brand_id", "summary", "createdTime", "creater_name", "creater_org","local_attr","cities", "enabled"};

    // 前后端Key

    /**
     * 获取查询语句
     */
    public String  getSqlExceptSelect(ConcurrentHashMap<String, String> searchInfo){
        String sqlExceptSelect = " from package where is_deleted = 0 ";

        int orgId = InterfaceUtil.getOrgId();
        String orgSql = InterfaceUtil.getChlidOrgIdSql(orgId, Constant.MAX_ORG_LEVEL, true);
        if(StrKit.notBlank(orgSql)){
            sqlExceptSelect += " and org_id in (" + orgSql + ") ";
        }

        boolean isSearchInfoEmpty = true;
        for(Entry<String, String> item : searchInfo.entrySet()){
            sqlExceptSelect += buildQuery(item);

            isSearchInfoEmpty = false;
        }

        // 如果非成都机构的人查询全部数据，不显示"营销活动选号入网"的数据
        if(isSearchInfoEmpty && !InterfaceUtil.isOrgChengdu(orgId) && !(orgId == InterfaceUtil.getIdTop())
                && !(InterfaceUtil.getAdminId() == 1)){
            sqlExceptSelect += " and type != 3";
        }

        sqlExceptSelect += " order by created_time desc ";

        // System.out.println("sqlExceptSelect = " + sqlExceptSelect);
        return sqlExceptSelect;
    }

    /**
     * @param searchInfo
     * @Title: getListExport
     * @Description:导出
     * @return List<Record>
     */
    public List<Record> getListExport(ConcurrentHashMap<String, String> searchInfo){
        String sqlHead = "select id,name,(case localized when 0 then '统一授权' else '属地化' end) as local_attr,( SELECT GROUP_CONCAT(DisplayName) AS a FROM ( SELECT localized_city_id, business_id FROM localized_config WHERE localized_config.business = "+ LocalizedConfig.TYPE_PACKAGE_XHRW+" ) AS localized_cities LEFT JOIN organization org ON org.id = localized_cities.localized_city_id WHERE localized_cities.business_id = package.id ) AS cities,(CASE type WHEN  0 THEN '普号' WHEN  1 THEN '靓号' WHEN  3 THEN '营销活动选号入网' ELSE '普号和靓号' END) as type,tariff_code,brand_id,format(monthly_charge,2) as monthly_charge,format(predeposited,2) as predeposited,summary,date_format(created_time,'%Y-%m-%d %H:%i:%S') as createdTime ,(select real_name from sys_user where sys_user.id = package.created_by)as creater_name,(select DisplayName from organization where organization.id = package.org_id) as creater_org,if(enabled=1,'是','否') as enabled ";
        String sqlExceptSelect = getSqlExceptSelect(searchInfo);
        List<Record> list = Db.find(sqlHead + sqlExceptSelect);
        return list;
    }

    public int convertToDBType(int type){

        switch(type){
            case 1:
                return 2;
            case 2:
                return 0;
            case 3:
                return 1;
            case 4:
                return 3;
            case 5:
                return 5;
            default:
                logger.error("ILLEGAL PACKAGE TYPE");
                return 4; // unkown type

        }

    }

    public int convertFromDBType(int type){

        switch(type){
            case 2:
                return 1;
            case 0:
                return 2;
            case 1:
                return 3;
            case 3:
                return 4;
            default:
                logger.error("ILLEGAL PACKAGE TYPE");
                return 5; // unkown type

        }

    }

    private String buildQuery(Entry<String, String> item){
        String sql = "";
        if(item.getKey().equals("type")){
            sql += " and type = " + convertToDBType(Integer.valueOf(item.getValue()));
        } else if(item.getKey().equals("tariff_code")){
            sql += " and tariff_code like '%" + item.getValue() + "%'";
        } else if(item.getKey().equals("name")){
            sql += " and name like '%" + item.getValue() + "%'";
        }else if(item.getKey().equals("localized")){
            sql += " and localized = " + item.getValue();
        }else if(item.getKey().equals("enabled")){
            sql += " and enabled = " + item.getValue();
        }
        return sql;
    }

    public ResultCode delete(Integer[] ids){
        StringBuffer sb = new StringBuffer();
        sb.append("update package set is_deleted = 1 " + " where id in(");
        if(ids.length > 0){
            for(int i = 0; i < ids.length; i++){
                // System.out.println("id:" + ids[i]);
                if(i == ids.length - 1){
                    sb.append("?");
                } else{
                    sb.append("?,");
                }
            }
            sb.append(")");
        } else{
            return ResultCode.PARAM_ERROR;
        }

        // System.out.println("package delete sb=" + sb);

        boolean result = Package.dao.update(sb.toString(), ids);
        if(result){
            return ResultCode.SUCCESS;
        } else{
            return ResultCode.FAILED;
        }

    }

    public JSONArray getPackagesByType(int type, int orgId){

        JSONArray array = new JSONArray();

        // List<Record> rList = Package.dao.getPackagesByType(type, orgId);
        List<Record> rList = Package.dao.getPackagesByTypeClient(type, orgId);
        if(rList.size() <= 0){
            return array;
        }

        for(Record r : rList){
            JSONObject obj = new JSONObject();
            obj.put(ClientApiConstant.Key.ID, r.getInt(Package.ID));
            obj.put(ClientApiConstant.Key.PACKAGE_NAME, r.getStr(Package.NAME));
            // 客户端：// 0 表示普号， 1 表示靓号，2 营销活动选号入网，后台：// 0 表示普号， 1 表示靓号，3 营销活动选号入网
            obj.put(ClientApiConstant.Key.TYPE, r.getInt(Package.TYPE) == 3 ? 2 : r.getInt(Package.TYPE));
            obj.put(ClientApiConstant.Key.BUSINESS_CODE, r.getStr(Package.TARIFF_CODE));
            obj.put(ClientApiConstant.Key.RATES, r.getDouble(Package.MONTHLY_CHARGE));
            obj.put(ClientApiConstant.Key.ADVANCEDEPOSIT_RATES, r.getDouble(Package.PREDEPOSITED));
            obj.put(ClientApiConstant.Key.FEATURE_DESCRIBE, r.getStr(Package.SUMMARY));
            obj.put(ClientApiConstant.Key.PACKAGE_DETAILS, r.getStr(Package.DETAILS));
            obj.put(ClientApiConstant.Key.CREATE_TIME, r.getDate(Package.CREATED_TIME));
            obj.put(ClientApiConstant.Key.CREATER_ID, r.getInt(Package.CREATED_BY));
            obj.put(ClientApiConstant.Key.APPID_PACKAGE, ClientApiConstant.APPKEY_DZG_VALUE);
            obj.put(ClientApiConstant.Key.JGID, r.getInt(Package.ORG_ID));
            obj.put(ClientApiConstant.Key.BRAND_ID, r.getStr(Package.BRAND_ID));
            array.put(obj);
        }

        return array;

    }
    
    /**
     * 根据多个id找到对应的code
     * @return
     */
    public String[] findCodesByIds(String[] ids){
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < ids.length; i++){
            if(i == ids.length - 1){
                sb.append(ids[i]);
            } else{
                sb.append(ids[i]+",");
            }
        }
        
        List<Record> records = Db.find("select tariff_code from package where id in("+sb.toString()+")");
        String[] codes = new String[records.size()];
        int i=0;
        for(Record record:records){
            codes[i++] = record.getStr(Package.TARIFF_CODE);
        }
        return codes;
    }
}
